import { useCallback } from 'react';
import { Alert } from 'react-native';
import { useAppContext } from '../context/AppContext';

export const useTasks = () => {
  const {
    state: { tasks, currentTask, editingTaskId },
    addTask,
    updateTask,
    deleteTask,
    toggleTask,
    setCurrentTask,
    setEditingTaskId,
  } = useAppContext();

  // 添加或更新任务
  const handleAddTask = useCallback(() => {
    if (currentTask.trim() === '') return;

    if (editingTaskId) {
      updateTask(editingTaskId, currentTask);
      setEditingTaskId(null);
    } else {
      addTask(currentTask);
    }
    setCurrentTask('');
  }, [currentTask, editingTaskId, addTask, updateTask, setCurrentTask, setEditingTaskId]);

  // 编辑任务
  const handleEditTask = useCallback((id: string) => {
    const task = tasks.find(t => t.id === id);
    if (task) {
      setCurrentTask(task.title);
      setEditingTaskId(id);
    }
  }, [tasks, setCurrentTask, setEditingTaskId]);

  // 删除任务（带确认）
  const handleDeleteTask = useCallback((id: string) => {
    Alert.alert(
      '确认删除',
      '确定要删除这个任务吗？',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '删除',
          style: 'destructive',
          onPress: () => deleteTask(id),
        },
      ]
    );
  }, [deleteTask]);

  // 切换任务完成状态
  const handleToggleTask = useCallback((id: string) => {
    toggleTask(id);
  }, [toggleTask]);

  // 取消编辑
  const cancelEdit = useCallback(() => {
    setEditingTaskId(null);
    setCurrentTask('');
  }, [setEditingTaskId, setCurrentTask]);

  return {
    tasks,
    currentTask,
    editingTaskId,
    setCurrentTask,
    handleAddTask,
    handleEditTask,
    handleDeleteTask,
    handleToggleTask,
    cancelEdit,
  };
};
